<template>
	<view>
		<u-form class="form" :model="model" :rules="rules" ref="uForm" :label-position="labelPosition">
			<u-form-item ref="uFormItemSummary" :label="'标题'" prop="summary" label-width="180"
				:label-position="summaryPropLabelPosition" :required="true">
				<u-input v-model="model.summary" :type="summaryPropInputType" :placeholder="'请输入标题'"
					height="100" maxlength="500" :disabled="disabled" />
			</u-form-item>
			<u-form-item ref="uFormItemUserList" label="参与人" prop="userList" label-width="180" label-position="top">
				<view>
					<scroll-view :scroll-top="scrollTop" :scroll-y="scrollY" :class="{'scroll-Y': isScroll}"
						@scroll="scroll">
						<u-tag :text="item.name" :type="uTagProps.type" v-for="(item, index) in model.userList"
							:key="item.userId" :index="item.userId" :shape="uTagProps.shape"
							:closeable="uTagProps.closeable" :mode="uTagProps.mode" :size="uTagProps.size"
							@close="doDeleteUser" class="uTagStyle">
						</u-tag>
					</scroll-view>
				</view>
				<u-button v-if="!isViewMode" slot="right" type="success" size="mini" @click="chooseGroupUsers">选择成员</u-button>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseGroupUsers"
					@submit="useGroupUsersSelected" :mode="popupMeetingUsers.mode"
					:multiple="popupMeetingUsers.multiple" :action="chooseUserUrl"
					:default-selected-user-list="defaultGroupMemberUserList">
				</js-choose-user-popup>
			</u-form-item>
			<u-form-item :label="'开始时间'" prop="startTime" label-width="180" :required="true">
				<u-input v-model="model.startTime"
					:type="disabled ? 'input' : 'select'" 
					@click="uPickerStartTime.show = !disabled" 
					placeholder="请选择开始时间" 
					:disabled="disabled">
				</u-input>
				<u-picker v-model="uPickerStartTime.show" :mode="uPickerStartTime.mode"
					:params="uPickerStartTime.params" @confirm="confirm4StartTime">
				</u-picker>
			</u-form-item>
			<u-form-item v-if="!showEndTime" label="持续时长" prop="duration" label-width="180" :required="true">
				<js-select v-model="duration" dict-type="wechat_living_duration" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择持续时长" :disabled="disabled" @input="durationChange">
				</js-select>
			</u-form-item>
			<u-form-item v-if="showEndTime" ref="uFormItemEndTime" label="结束时间" prop="endTime" label-width="180" :required="true">
				<u-input v-model="model.endTime"
					:type="disabled ? 'input' : 'select'"
					@click="uPickerEndTime.show = !disabled" 
					placeholder="请选择结束时间" 
					:disabled="disabled">
				</u-input>
				<u-picker v-model="uPickerEndTime.show" :mode="uPickerEndTime.mode" :params="uPickerEndTime.params"
					@confirm="confirm4EndTime">
				</u-picker>
			</u-form-item>
			<u-form-item label="描述" prop="description" label-width="180" label-position="top">
				<u-input v-model="model.description" type="textarea" placeholder="请输入描述" height="100" maxlength="500"
					:disabled="disabled" />
			</u-form-item>
			<u-form-item label="日程地址" prop="location" label-width="180">
				<u-input v-model="model.location" placeholder="请输入日程地址" type="text" maxlength="64"
					style="text-align: left;" :disabled="disabled">
				</u-input>
			</u-form-item>
			<u-form-item label="是否要提醒" prop="isRemind" label-width="auto" :required="true">
				<u-switch v-model="isRemindChecked" active-value="1" inactive-value="0" @change="isRemindChange"
					:disabled="disabled">
				</u-switch>
			</u-form-item>
			<u-form-item v-if="showRemindBeforeEventSecs" :label="remindBeforeEventSecsPropLabel"
				prop="remindBeforeEventSecs" label-width="auto">
				<js-select v-model="model.remindBeforeEventSecs" dict-type="wechat_remind_before_event_secs"
					itemLabel="dictValue" itemValue="dictKey" :placeholder="'请选择' + remindBeforeEventSecsPropLabel"
					:disabled="disabled">
				</js-select>
			</u-form-item>
			<!-- 预留空一个u-form-item 解决相邻2个js-select数据加载问题 -->
			<!-- <u-form-item style="display: none;"></u-form-item> -->
			<repeat-setting :parent-name="repeatSettingProps.parentName"></repeat-setting>
		</u-form>
		<slot name="formFooterBtns" :msgGrandson="{'content':'Hi,I am grandson!'}">
			<view class="fixed-button-container">
				<u-button type="default" shape="circle" @click="cancel">{{isViewMode ? '返回' : '取消'}}</u-button>
				<u-button v-if="!isViewMode" type="primary" shape="circle" @click="submit">保存</u-button>
			</view>
		</slot>
	</view>
</template>
<script>
	import WechatUpload from '@/pages/wechat/wechat-upload.vue';
	import RepeatSetting from '@/pages/wechat/wechatSchedule/comp/common/repeatSetting.vue';

	export default {
		name: 'schedule-form',
		components: {
			WechatUpload,
			RepeatSetting
		},
		props: {
			/**
			 * 初始表单数据
			 */
			initialModel: {
				type: Object,
				default: () => ({})
			},
			/**
			 * 模式：add、edit、view
			 */
			modeProp: {
				type: String,
				default: 'view'
			},
		},
		data() {
			return {
				model: {
					// 当前组件提醒类型：默认为1（日程）
					remindType: '1',
					summary: '',
					attendees: '',
					startTime: '',
					endTime: '',
					description: '',
					location: '',
					userList: [],
					// 是否提醒，默认0（否）
					isRemind: '0',
					remindBeforeEventSecs: '',
					//是否重复：默认0（否）
					isRepeat: '0',
					// 重复类型
					repeatType: '',
					repeatUntil: '',
					// 是否自定义重复，默认0（否）
					isCustomRepeat: '0',
					frequency: '',
					repeatInterval: '',
					repeatDayOfWeek: '',
					repeatDayOfMonth: '',
					attach: ''
				},
				// 操作模式：view、add、edit
				mode: '',
				// 默认3600秒（1个小时）
				duration: '3600',
				uPickerStartTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					}
				},
				uPickerEndTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					}
				},
				uPickerRepeatUntil: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					}
				},
				uTagProps: {
					mode: 'light',
					type: 'primary',
					size: 'default',
					shape: 'square',
					closeable: true
				},
				summaryPropLabel: '标题',
				summaryPropInputType: 'textarea',
				summaryPropLabelPosition: 'top',
				startTimePropLabel: '开始时间',
				remindBeforeEventSecsPropLabel: '开始前多久提醒',
				//是否显示~结束时间表单项
				showEndTime: false,
				//是否显示~开始前多久提醒
				showRemindBeforeEventSecs: false,
				labelPosition: 'left',
				disabled: false,
				rules: {
					remindType: [{
						required: true,
						message: '请选择提醒类型',
						trigger: 'change'
					}],
					summary: [{
						validator: (rule, value, callback) => {
							if (value) {
								callback();
							} else {
								let message = '请输入' + this.summaryPropLabel;
								callback(new Error(message));
							}
						},
						trigger: 'blur'
					}],
					startTime: [{
						validator: (rule, value, callback) => {
							if (value) {
								callback();
							} else {
								let message = '请选择' + this.startTimePropLabel;
								callback(new Error(message));
							}
						},
						trigger: 'change'
					}],
					duration: [{
						validator: (rule, value, callback) => {
							// duration不是model对象的属性，所以value没有值
							let validateResult = true;
							let duration = this.duration;
							if (!this.showEndTime && !duration) {
								validateResult = false;
							}
							return validateResult;
						},
						message: '请选择持续时长',
						trigger: 'change'
					}],
					endTime: [{
							required: true,
							message: '请选择结束时间',
							trigger: 'change',
						},
						{
							validator: (rule, value, callback) => {
								if (this.model.remindType != '1') {
									//非日程则不检验
									callback();
								}
								let endTime = new Date(value);
								if (this.model.startTime) {
									let startTime = new Date(this.model.startTime);
									if (endTime.getTime() < startTime.getTime()) {
										callback(new Error('结束时间不能小于开始时间'));
									} else {
										callback();
									}
								} else {
									callback(new Error('请先选择开始时间'));
								}
							},
							trigger: 'change'
						}
					],
					// 验证规则的type属性默认类型为string，而在详情接口返回中liveType是数值，
					// 发生'liveType is not a string'，从而在编辑页面中提示检验不通过。
					// 解决方法指定type: 'number'，或validator自定义方法。
					repeatType: [{
						validator: (rule, value, callback) => {
							return (value || value === 0) ? true : false;
						},
						message: '请选择重复类型',
						trigger: 'change'
					}],
					frequency: [{
						required: true,
						type: 'number',
						message: '请选择自定义频率',
						trigger: 'change'
					}],
					repeatInterval: [{
						required: true,
						type: 'number',
						message: '请选择重复间隔',
						trigger: 'change'
					}]
				},
				labelPosition: 'left',
				chooseUserUrl: '/api/blade-system/user/user-list-by-dept-type',
				popupMeetingUsers: {
					show: false,
					mode: "bottom",
					multiple: true,
				},
				isScroll: true,
				scrollTop: 0,
				scrollY: true,
				old: {
					scrollTop: 0
				},
				checkboxGroupProps: {
					width: 'auto',
					wrap: false
				},
				dictDataOptions: {
					'wechatYesNo': []
				},
				//已有的附件列表
				attachFileList: [],
				upload: {
					deletable: true,
					maxCount: 5,
					maxSize: 10 * 1024 * 1024
				},
				isRemindChecked: false,
				repeatSettingProps: {
					parentName: ''
				},
			};
		},
		computed: {
			/**
			 * 返回是否初始化选择用户组件的标识
			 * 解决父组件将请求回来的数据传递给子组件的延迟问题
			 */
			useInitChooseUserComp: function() {
				let useInit = false;
				if (this.mode === 'add' || this.mode === 'edit') {
					useInit = true;
				}
				return useInit;
			},
			defaultGroupMemberUserList: function() {
				let userList = this.model.userList.map(user => {
					return {
						id: user.userId,
						name: user.name,
					}
				});
				return userList;
			},
			getStartTimePropLabel: function() {
				return '请选择' + this.startTimePropLabel;
			},
			isViewMode: function() {
				return this.mode === 'view';
			},
		},
		watch: {
			'model.userList': function(val, oldVal) {
				// 通知将当前的值发送到 userList的u-form-item组件中进行校验
				if (this.$refs.uFormItemUserList) {
					this.$refs.uFormItemUserList.$emit('on-form-change', val);
				}
			},
			'model.isRemind': function(val, oldVal) {
				if (val == '1') {
					this.isRemindChecked = true;
					this.showRemindBeforeEventSecs = true;
				} else if (val == '0') {
					this.isRemindChecked = false;
					this.showRemindBeforeEventSecs = false;
				}
			},
			'model.startTime': function(val, oldVal) {
				if (val && this.$refs.uFormItemEndTime) {
					this.$refs.uFormItemEndTime.$emit('on-form-change');
				}
			}
		},
		beforeCreate() {
			
		},
		onLoad(params) {
			// onLoad 属于页面生命周期 路由跳转到当前组件才会执行到
			// 其参数为上个页面传递的数据，参数类型为 Object（用于页面传参），参考示例(https://uniapp.dcloud.net.cn/api/router.html#navigateto)。
			// this.$route.query 也能获取同样的参数
		},
		created() {
			this.repeatSettingProps.parentName = this.$options.name;
			this.model = Object.assign({}, this.model, this.initialModel);
			this.mode = this.modeProp;
			this.initData();
		},
		onReady() {
			// onReady 属于页面生命周期 路由跳转到当前组件才会执行到
		},
		beforeMount() {
			
		},
		mounted() {
			// mounted 属于组件生命周期
			// 当前组件如果直接路由加载的话，下行代码可以写在onReady中。目前当前组件是在formContainer.vue中被引用，所以要写在mounted中。
			// 在组件中使用表单校验 可以统一写在mounted勾子方法中。
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			initData() {
				let id = this.model.id;
				if (id) {
					this.showEndTime = true;
					if (this.mode == "view") {
						this.disabled = true;
						this.uTagProps.closeable = false;
					} else {
						this.disabled = false;
						this.uTagProps.closeable = true;
					}
				} else {
					// id为空则默认表示mode为add
					this.disabled = false;
				}
			},
			/**
			 * 日程类型：让当前用户一定在参与人之中
			 */
			// addCurrentUser2Attendees() {
			// 	let isExisted = this.model.userList.some((element) => element.userId == this.vuex_userId);
			// 	if(!isExisted) {
			// 		let currentUser = {
			// 			"name": this.vuex_realName,
			// 			"userId": this.vuex_userId
			// 		};
			// 		this.model.userList.push(currentUser);
			// 	}
			// },
			durationChange(val) {
				//自定义时间
				if (val == 4) {
					this.model.endTime = '';
					this.showEndTime = true;
					//将回调延迟到下次 DOM 更新循环之后执行
					this.$nextTick(() => {
						if (this.$refs.uFormItemEndTime) {
							this.$refs.uFormItemEndTime.$emit('on-form-change')
						}
					});
				}
			},
			initDefaultAttachFileList() {
				let attach = this.model.attach;
				if (attach) {
					let attachList = attach.split(',');
					attachList.forEach(element => {
						this.attachFileList.push({
							url: element
						});
					})
				}
			},
			getPickerResult(e, params) {
				let pickerResult = '';
				if (params.year) {
					pickerResult += e.year;
				}
				if (params.month) {
					pickerResult += '-' + e.month;
				}
				if (params.day) {
					pickerResult += '-' + e.day;
				}
				if (params.hour) {
					pickerResult += ' ' + e.hour;
				}
				if (params.minute) {
					pickerResult += ':' + e.minute;
				}
				if (params.second) {
					pickerResult += ':' + e.second;
				}
				return pickerResult;
			},
			confirm4StartTime(e) {
				this.model.startTime = this.getPickerResult(e, this.uPickerStartTime.params);
				this.uPickerStartTime.show = false;
			},
			confirm4EndTime(e) {
				this.model.endTime = this.getPickerResult(e, this.uPickerEndTime.params);
				this.uPickerEndTime.show = false;
			},
			chooseGroupUsers() {
				this.$refs.chooseGroupUsers.open();
				this.$refs.chooseGroupUsers.setDefaultSelectedUserList(this.defaultGroupMemberUserList);
			},
			useGroupUsersSelected() {
				let groupUsers = this.$refs.chooseGroupUsers.getData();
				if (groupUsers.length > 0) {
					this.model.userList = [];
				}
				groupUsers.forEach((element) => {
					this.model.userList.push({
						"name": element.name,
						"userId": element.id
					});
				});
				this.$refs.chooseGroupUsers.close();
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			doDeleteUser: function(userId) {
				this.model.userList = this.model.userList.filter(user => userId != user.userId);
				this.$refs.chooseGroupUsers.$emit('remove-selected-user-by-id', userId);
			},
			getAttachFileList() {
				let files = this.$refs.attachUpload.getFileList();
				let fileUrlList = [];
				files.forEach(item => {
					if (item.response) {
						//当前新上传的文件
						let data = item.response.data;
						const {
							link
						} = data;
						fileUrlList.push(link);
					} else {
						//默认已有的文件
						const {
							url
						} = item;
						fileUrlList.push(url);
					}
				})
				return fileUrlList;
			},
			doBeforeModelPost: function() {
				if (!this.showEndTime) {
					//根据持续时长计算结束时间
					let startTime = new Date(this.model.startTime);
					let secondsOfEndTime = startTime.setSeconds(startTime.getSeconds() + parseInt(this.duration));
					this.model.endTime = this.$u.timeFormat(secondsOfEndTime, 'yyyy-mm-dd hh:MM:ss');
				}
				if (this.model.userList.length > 0) {
					let userIds = this.model.userList.map(user => user.userId);
					this.model.attendees = userIds.join(',');
				}
			},
			isRemindChange(value) {
				this.model.isRemind = value;
			},
			submit() {
				let vm = this;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '提交中....'
						})
						this.doBeforeModelPost();
						let promise = this.$u.api.wechat.wechatSchedule.save(this.model);
						promise.then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function() {
									if (res.code == 200) {
										vm.cancel();
									}
								}
							});
						});
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			cancel() {
				let navigateBackUrl = this.$route.query.navigateBackUrl;
				if(navigateBackUrl) {
					this.$u.route({
						url:navigateBackUrl
					});
				}else {
					uni.navigateBack();
				}
			},
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.uTagStyle {
		margin-right: 10rpx;
	}

	.scroll-Y {
		height: 200rpx;
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		background: #FFFFFF !important;
	}
	
	.fixed-button-container {
		display: flex; 
		flex-direction: row;
		justify-content: center;
		width: 100%;
		
		padding: 0 10rpx;
		button {
			width: 50%;
		}
		button + button {
			margin-left: 10rpx;
			margin-bottom: 10rpx;
		}
	}
</style>